

import BaseObj from "./BaseObj";
import ObjContainer from "./ObjContainer";
import Player from "./Player";



export default class MessageHandlers {

    private static _instance: MessageHandlers | null;
    private constructor() { }

    public static instance() {
        if (MessageHandlers._instance == null) {
            MessageHandlers._instance = new MessageHandlers()
        }
        return MessageHandlers._instance;
    }

    //服务器返回本地用户信息
    public userInfo = (data: any) => {
        let userInfoData = data as { type: string, userId: number }
        let player = new Player(userInfoData.userId)
        ObjContainer.addObj(player)
    }
    //服务器返回用户位置信息
    public position = (data: any) => {
        let positionData = data as { type: string, userId: number, x: number, y: number }
        let container = ObjContainer.container
        for (let obj of container) {
            if (obj instanceof Player) {
                if (obj.userId === positionData.userId && obj.isLocal) continue

                if (obj.userId === positionData.userId) {
                    obj.x = positionData.x
                    obj.y = positionData.y
                    return
                }
            }
        }

    }
    //服务器返回新用户加入
    public newPlayer = (data: any) => {
        let newPlayerData = data as { type: string, userIds: number[] }
        newPlayerData.userIds.forEach((userId) => {
            let newplayer = new Player(userId, false)
            newplayer.color = "blue"
            ObjContainer.addObj(newplayer)
        })

    }

    public removePlayer = (data: any) => {
        let removePlayerData = data as { type: string, userId: number }
        let container = ObjContainer.container
        let deleteObj: BaseObj | null = null
        for (let obj of container) {
            if (obj instanceof Player) {
                if (obj.userId === removePlayerData.userId) {
                    deleteObj = obj
                    break
                }
            }
        }
        if (deleteObj) {
            container.delete(deleteObj)
        }

    }
}